package com.yuanli.card.manage.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;


@Configuration
public class ServiceConfig extends WebMvcConfigurerAdapter {
    
    // ======日期转换器起====== //
  	private static Pattern pattern1 = Pattern.compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}");
  	private static Pattern pattern2 = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
  	private static Pattern pattern3 = Pattern.compile("\\d{2}-\\d{2}-\\d{2}");
  	@Bean
  	public Converter<String, Date> strToDate() {
  		return new Converter<String, Date>() {
  			@Override
  			public Date convert(String dateStr) {
  				try {
  					if (pattern1.matcher(dateStr).find()) return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
  					if (pattern2.matcher(dateStr).find()) return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
  					if (pattern3.matcher(dateStr).find()) return new SimpleDateFormat("HH:mm:ss").parse(dateStr);
  				} catch (ParseException e) {
  					e.printStackTrace();
  				}
  				return null;
  			}
  		};
  	}


    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converter.setObjectMapper(objectMapper);
        return converter;
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
        converters.add(mappingJackson2HttpMessageConverter());
        super.configureMessageConverters(converters);
    }

}
